<?php
/**
 * @package		简易CMS
 * @subpackage	插件函数包
 * @version		$Id: option_misc.php 26 2012-09-23 16:03:32Z htmambo@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2010 Hoping Software Studio.
 */

if (!defined('IN_JYCMS')) {
	exit('Access Denied');
}
define('NOROBOT', TRUE);
define('CURSCRIPT', 'misc');

class misc_ctrl extends application {

	var $allowaction = array(
		'ajax', 'click', 'editor', 'initsys', 'ranklist', 'report', 'sendmail', 'gettags', 'tag', 'search', 'tagcloud'
	);

	function __construct() {
		$this->misc_ctrl();
	}

	function misc_ctrl() {
		parent::__construct();
	}
	function onTagCloud(){
			@header("Expires: -1");
			@header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", FALSE);
			@header("Pragma: no-cache");
			@header("Content-type: application/xml; charset=" . CHARSET);
			echo '<' . "?xml version=\"1.0\" encoding=\"" . CHARSET . "\"?>\n";
			echo '
			<root>
			<item type="text" detail="雾灵山" link="http://top.baidu.com/detail.php?b=14&amp;w=%CE%ED%C1%E9%C9%BD" weight="40" />
			</root>';
		exit();
	}
	function onSearch() {
		global $_G;
		if (!$_G['setting']['search']['status']) {
			showmessage('Search article has been closed, please return!');
		}
		if ($_G['adminid'] != 1 && !($_G['group']['allowsearch'] & 1)) {
			showmessage('group_nopermission', NULL, array('grouptitle' => $_G['group']['grouptitle']), array('login' => 1));
		}
		$_G['setting']['search']['searchctrl'] = intval($_G['setting']['search']['searchctrl']);
		$srchmod = 1;
		$cachelife_time = 300;  // Life span for cache of searching in specified range of time
		$cachelife_text = 3600;  // Life span for cache of text searching
		$srchtype = empty($_G['gp_srchtype']) ? '' : trim($_G['gp_srchtype']);
		$searchid = isset($_G['gp_searchid']) ? intval($_G['gp_searchid']) : 0;
		$srchtxt = $_G['gp_srchtxt'];
		$keyword = isset($srchtxt) ? htmlspecialchars(trim($srchtxt)) : '';
		if (!submitcheck('searchsubmit', 1)) {
			$pageTitle ='搜索';
			include template('search/portal');
		} else {
			$orderby = in_array($_G['gp_orderby'], array('aid')) ? $_G['gp_orderby'] : 'aid';
			$ascdesc = isset($_G['gp_ascdesc']) && $_G['gp_ascdesc'] == 'asc' ? 'asc' : 'desc';
			if (!empty($searchid)) {
				$page = max(1, intval($_G['gp_page']));
				$start_limit = ($page - 1) * $_G['tpp'];
				$index = DB::fetch_first("SELECT searchstring, keywords, num, ids FROM #__common_searchindex WHERE searchid='$searchid' AND srchmod='$srchmod'");
				if (!$index) {
					showmessage('search_id_invalid');
				}
				$keyword = htmlspecialchars($index['keywords']);
				$pageTitle = '《'.$keyword.'》的搜索结果，共'.$index['num'].'篇';
				$keyword = $keyword != '' ? str_replace('+', ' ', $keyword) : '';
				$index['keywords'] = rawurlencode($index['keywords']);
				$aids = $index['ids'];
				$multipage = multi($index['num'], 10, $page, "index.php?option=misc&task=search&searchid=$searchid&orderby=$orderby&ascdesc=$ascdesc&searchsubmit=yes");
				include template('search/portal');
			} else {
				$searchstring = 'portal|title|' . addslashes($srchtxt);
				$searchindex = array('id' => 0, 'dateline' => '0');
				$query = DB::query("SELECT searchid, dateline,
			('" . $_G['setting']['search']['searchctrl'] . "'<>'0' AND " . (empty($_G['uid']) ? "useip='$_G[clientip]'" : "uid='$_G[uid]'") . " AND $_G[timestamp]-dateline<'" . $_G['setting']['search']['searchctrl'] . "') AS flood,
			(searchstring='$searchstring' AND expiration>'$_G[timestamp]') AS indexvalid
			FROM #__common_searchindex
			WHERE srchmod='$srchmod' AND ('" . $_G['setting']['search']['searchctrl'] . "'<>'0' AND " . (empty($_G['uid']) ? "useip='$_G[clientip]'" : "uid='$_G[uid]'") . " AND $_G[timestamp]-dateline<" . $_G['setting']['search']['searchctrl'] . ") OR (searchstring='$searchstring' AND expiration>'$_G[timestamp]')
			ORDER BY flood");
				while ($index = DB::fetch($query)) {
					if ($index['indexvalid'] && $index['dateline'] > $searchindex['dateline']) {
						$searchindex = array('id' => $index['searchid'], 'dateline' => $index['dateline']);
						break;
					} elseif ($_G['adminid'] != '1' && $index['flood']) {
						showmessage('search_ctrl', 'index.php?option=misc&task=search', array('searchctrl' => $_G['setting']['search']['searchctrl']));
					}
				}
				if ($searchindex['id']) {
					$searchid = $searchindex['id'];
				} else {
					if (!$srchtxt) {
						dheader('Location: index.php?option=misc&task=search');
					}
					if ($_G['adminid'] != '1' && $_G['setting']['search']['maxspm']) {
						if ((DB::result_first("SELECT COUNT(*) FROM #__common_searchindex WHERE srchmod='$srchmod' AND dateline>'$_G[timestamp]'-60")) >= $_G['setting']['search']['maxspm']) {
							showmessage('search_toomany', 'index.php?option=misc&task=search', array('maxspm' => $_G['setting']['search']['maxspm']));
						}
					}
					$num = $ids = 0;
					$_G['setting']['search']['maxsearchresults'] = $_G['setting']['search']['maxsearchresults'] ? intval($_G['setting']['search']['maxsearchresults']) : 500;
					$srchtxtsql = addcslashes($srchtxt, '%_');
					$query = DB::query("SELECT aid FROM #__portal_article_title WHERE title LIKE '%$srchtxtsql%' ORDER BY aid DESC LIMIT " . $_G['setting']['search']['maxsearchresults']);
					while ($article = DB::fetch($query)) {
						$ids .= ',' . $article['aid'];
						$num++;
					}
					DB::free_result($query);
					$keywords = str_replace('%', '+', $srchtxt);
					$expiration = TIMESTAMP + $cachelife_text;
					DB::query("INSERT INTO #__common_searchindex (srchmod, keywords, searchstring, useip, uid, dateline, expiration, num, ids)
					VALUES ('$srchmod', '$keywords', '$searchstring', '$_G[clientip]', '$_G[uid]', '$_G[timestamp]', '$expiration', '$num', '$ids')");
					$searchid = DB::insert_id();
				}
				dheader("location: index.php?option=misc&task=search&searchid=$searchid&searchsubmit=yes");
			}
		}
	}

	function onTag() {
		global $_G;
		$tag = $this->get['tag'];
		$tagid = $this->get['tagid'];
		if (!$tag && !$tagid) {
			showmessage('对不起，您没有指定要查询的标签！');
		}
		$where = '';
		if ($tagid) {
			$where = 'a.tagid=' . $tagid;
		} else {
			$where = "tagname='$tag'";
		}
		$aids = '';
		DB::query("SELECT tagname, itemid, tagtype FROM #__common_tags a LEFT JOIN #__common_tagslist b on a.tagid=b.tagid WHERE $where");
		$total = 0;
		$rows = DB::fetch_all();
		if ($rows) {
			$total = count($rows);
			$aids = array();
			foreach ($rows as $v)
				$aids[] = $v['itemid'];
			$aids = implode(',', $aids);
		}
		if (!$aids) {
			showmessage('对不起，没有找到符合条件的记录！');
		}
		$pageTitle = '标签《'.$tag.'》的搜索结果，共'.$total.'篇';
		$page = max(1, intval($_GET['page']));
		$multipage = multi($total, 10, $page, "index.php?option=misc&task=tag&tag=$tag");
		include template('search/portal');
	}

	function onGetTags() {
		$content = trim($_POST['content']);
		$content = strip_tags($content);
		$result = '选择推荐标签来源';
		$action = $this->get['action'];
		$action = (in_array($action, array('local', 'discuz', 'split'))) ? $action : 'split';
		if ($action == 'split') {
			if (!isset($cnsp)) {
				require_once libfile('class/splitword');
				$cnsp = new SplitWord ();
			}
			$cnsp->SetSource($content);
			$cnsp->StartAnalysis();
			$keywords = $cnsp->GetFinallyIndex(10);
			if ($keywords) {
				$result = '';
				foreach ($keywords as $v) {
					$result.='<span>' . $v['word'] . '</span>';
				}
			}
		} elseif ($action == 'discuz') {
			// Get data
			$subjectenc = rawurlencode(strip_tags(iconv(CHARSET, 'GBK', $_POST['title'])));
			$messageenc = rawurlencode(substr(strip_tags(iconv(CHARSET, 'GBK', $_POST['content'])), 0, 1000));
			$url = 'http://keyword.discuz.com/related_kw.html?ics=gbk&ocs=' . strtolower(CHARSET) . '&title=' . $subjectenc . '&content=' . $messageenc;
			$data = dfsockopen($url);
			if ($data) {
				$result = '';
				$parser = xml_parser_create();
				xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
				xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
				xml_parse_into_struct($parser, $data, $values, $index);
				xml_parser_free($parser);
				foreach ($values as $valuearray) {
					if (strlen($valuearray['value']) > 3)
						if ($valuearray['tag'] == 'kw' || $valuearray['tag'] == 'ekw') {
							$result .= '<span>' . trim($valuearray['value']) . '</span>' . "\n";
						}
				}
			}
		} else {

		}
		exit($result);
	}

	function onAjax() {
		global $_G;
		if ($_G['gp_action'] == 'checkusername') {

			include_once libfile('function/member');
			$username = trim($_G['gp_username']);
			$ucresult = check_username($username);

			if ($ucresult == -1) {
				showmessage('User name contains sensitive characters');
			} elseif ($ucresult == -2) {
				showmessage('Shielded by the system user name contains characters');
			} elseif ($ucresult == -3) {
				if (DB::result_first("SELECT uid FROM #__common_member WHERE username='$username'")) {
					showmessage('The user name already used by others');
				} else {
					showmessage('The user name already exists');
				}
			}
		} elseif ($_G['gp_action'] == 'checkemail') {
			include_once libfile('function/member');

			$email = trim($_G['gp_email']);
			$ucresult = check_email($email);

			if ($ucresult == -4) {
				showmessage('The email address is invalid');
			} elseif ($ucresult == -5) {
				showmessage('Email contains the mailbox name not be used');
			} elseif ($ucresult == -6) {
				showmessage('The Email address is already registered');
			}
		} elseif ($_G['gp_action'] == 'checkuserexists') {

			$check = DB::result_first("SELECT uid FROM #__common_member WHERE username='" . trim($_G['gp_username']) . "'");
			$check ? showmessage('<img src="' . IMGDIR . '/check_right.gif" width="13" height="13">', '', array(), array('msgtype' => 3)) : showmessage('Specifies the user does not exist, please return to modified.', '', array(), array('msgtype' => 3));
		} elseif ($_G['gp_action'] == 'displaysearch_adv') {
			$display = $_G['gp_display'] == 1 ? 1 : '';
			dsetcookie('displaysearch_adv', $display);
		}
		showmessage($_G['setting']['reglinkname']);
	}

	function onClick() {
		global $_G;
		$clickid = empty($_GET['clickid']) ? 0 : intval($_GET['clickid']);
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		loadcache('click');
		$clicks = empty($_G['cache']['click']['aid']) ? array() : $_G['cache']['click']['aid'];
		$click = $clicks[$clickid];

		if (empty($click) || IS_ROBOT) {
			showmessage('The normal operating position without!');
		}

		$sql = "SELECT a.* FROM #__portal_article_title a
					LEFT JOIN #__portal_article_content af ON af.aid=a.aid
					WHERE a.aid='$id'";
		$query = DB::query($sql);
		if (!$item = DB::fetch($query)) {
			showmessage('To position the object does not exist!');
		}

		$hash = md5($item['uid'] . "\t" . $item['dateline']);
		if ($_GET['op'] == 'add') {
			if (!checkperm('allowclick') || $_GET['hash'] != $hash) {
				showmessage('You are not currently have permission to do!');
			}
			if ($item['uid'] == $_G['uid'] && $_G['uid']) {
				showmessage('Does not allow you to position yourself!');
			}

			if ($_G['uid']) {
				$where = "uid='$_G[uid]' AND ";
			} else {
				$where = "username='$_G[clientip]' AND ";
				$_G['username'] = $_G['clientip'];
			}
			$query = DB::query("SELECT * FROM #__common_clickuser WHERE $where id='$id'");
			if ($value = DB::fetch($query)) {
				showmessage('You have a position!');
			}
			$setarr = array(
				'uid' => $space['uid'],
				'username' => $_G['username'],
				'id' => $id,
				'clickid' => $clickid,
				'dateline' => $_G['timestamp']
			);
			DB::insert('common_clickuser', $setarr);

			DB::query("UPDATE #__portal_article_title SET click{$clickid}=click{$clickid}+1 WHERE aid='$id'");

			$note_type = '';
			$q_note = '';
			$q_note_values = array();

			$note_type = 'clickarticle';
			$q_note = 'click_article';
			$q_note_values = array(
				'url' => "index.php?task=view&aid=$item[aid]",
				'subject' => $item['title'],
				'from_id' => $item['aid'],
				'from_idtype' => 'aid'
			);

			updatecreditbyaction('click', 0, array(), 'aid' . $id);

			notification_add($item['uid'], $note_type, $q_note, $q_note_values);

			showmessage('In position complete!', '', array('idtype' => 'aid', 'id' => $id, 'clickid' => $clickid), array('msgtype' => 3, 'showmsg' => true, 'closetime' => true));
		} elseif ($_GET['op'] == 'show') {
			$maxclicknum = 0;
			foreach ($clicks as $key => $value) {
				$value['clicknum'] = $item["click{$key}"];
				$value['classid'] = mt_rand(1, 4);
				if ($value['clicknum'] > $maxclicknum)
					$maxclicknum = $value['clicknum'];
				$clicks[$key] = $value;
			}
			$count = getcount('common_clickuser', array('id' => $id));
		}
		include_once(template('portal/click'));
	}

	function onInitSys() {
		global $_G;

		if ($_G['adminid'] != 1 && $_G['setting']['styles']) {
			echo '<pre>';
			print_r($_G['setting']);
			exit('<div id="result">Access Denied!</div>');
		}

		require_once libfile('function/cache');
		updatecache();

		$cachelist = array('setting', 'usergroups', 'admingroups');
		loadcache($cachelist);

		require_once libfile('function/block');
		blockclass_cache();

		if ($_G['config']['output']['tplrefresh']) {
			$tpl = dir(ROOT_PATH . './data/template');
			while ($entry = $tpl->read()) {
				if (preg_match("/\.tpl\.php$/", $entry)) {
					@unlink(ROOT_PATH . './data/template/' . $entry);
				}
			}
			$tpl->close();
		}
		exit('<div id="result">Ok!</div>');
	}

	function onRankList() {
		global $_G, $page, $cache_time, $cache_num, $dateline, $orderby;
		define('CLOSEBANNED', 1);
		require_once libfile('function/ranklist');
		if (!$_G['gp_orderby'])
			$_G['gp_orderby'] = 'heats';
		$page = $_G['page'];

		$ranklist_setting = $_G['setting']['ranklist']['article'];
		if (!$ranklist_setting['available']) {
			showmessage('Ranklist is not enabled!');
		}
		$navtitle = lang('core', 'Ranklist');

		$cache_time = $ranklist_setting['cache_time'];
		$cache_num = $ranklist_setting['show_num'];
		if ($cache_time <= 0)
			$cache_time = 5;
		$cache_time = $cache_time * 3600;
		if ($cache_num <= 0)
			$cache_num = 20;

		loadcache('click');
		$clicks = empty($_G['cache']['click']['aid']) ? array() : $_G['cache']['click']['aid'];

		$articlelist = '';
		$before = '604800';
		switch ($_G['gp_before']) {
			case 'all':
				$before = '0';
				break;
			case 'today':
				$before = '86400';
				break;
			case 'thisweek':
				$before = '604800';
				break;
			case 'thismonth':
				$before = '2592000';
				break;
			default: $_G['gp_before'] = 'thisweek';
		}
		$orderby = 'dateline DESC';
		$navname = $_G['setting']['sitename'];
		switch ($_G['gp_orderby']) {
			case 'heats':
				$orderby = 'a.dateline DESC';
				$navtitle = lang('ranklist', 'Latest') . ' - ' . $navname;
				$metakeywords = lang('ranklist', 'Latest meta keywords');
				$metadescription = lang('ranklist', 'Latest meta description');
				break;
			case 'replies':
				$orderby = 'a.commentnum DESC';
				$navtitle = lang('ranklist', 'Most replies') . ' - ' . $navname;
				$metakeywords = lang('ranklist', 'Most replies meta keywords');
				$metadescription = lang('ranklist', 'Most replies meta description');
				break;
			case 'views':
				$orderby = 'a.viewnum DESC';
				$navtitle = lang('ranklist', 'Most viewed') . ' - ' . $navname;
				$metakeywords = lang('ranklist', 'Most viewed meta keywords');
				$metadescription = lang('ranklist', 'Most viewed meta description');
				break;
			default:
				if ($clicks[$_G['gp_orderby']]) {
					$orderby = 'click' . $_G['gp_orderby'] . ' DESC';
					$navtitle = $clicks[$_G['gp_orderby']]['name'] . lang('ranklist', 'ranklist') . ' - ' . $navname;
				} else {
					$_G['gp_orderby'] = 'a.dateline desc';
				}
		}

		$dateline = !empty($before) ? TIMESTAMP - $before : 0;

		$articlelist = getranklistcache_article();
		global $lastupdate, $nextupdate;
		$lastupdate = $articlelist['lastupdate'];
		$nextupdate = $articlelist['nextupdate'];

		unset($articlelist['lastupdated'], $articlelist['lastupdate'], $articlelist['nextupdate']);

		$urladd = '';
		if ($_G['gp_orderby']) {
			$urladd .= "&orderby={$_G['gp_orderby']}";
		}
		if ($_G['gp_before']) {
			$urladd .= "&before={$_G['gp_before']}";
		}

		include template('diy:portal/ranklist');
	}

	function onReport() {
		global $_G;
		if (empty($_G['uid'])) {
			showmessage('Sorry, you have not logged in, can not do this.', null, array(), array('login' => 1));
		}
		$rtype = $_G['gp_rtype'];
		$rid = $_G['gp_rid'];
		$default_url = array(
			'user' => 'index.php?option=member&task=profile&uid=',
		);
		$url = '';
		if ($rid && !empty($default_url[$rtype])) {
			$url = $default_url[$rtype] . intval($rid);
		} else {
			$url = addslashes(dhtmlspecialchars(base64_decode($_G['gp_url'])));
			$url = preg_match("/^http[s]?:\/\/[^\[\"']+$/i", trim($url)) ? trim($url) : '';
		}
		if (empty($url) || empty($_G['inajax'])) {
			showmessage('Page parameter error, temporarily unable to report.');
		}
		$urlkey = md5($url);
		if (submitcheck('reportsubmit')) {
			$message = censor(cutstr(dhtmlspecialchars(trim($_G['gp_message'])), 200, ''));
			$message = $_G['username'] . '&nbsp;:&nbsp;' . rtrim($message, "\\");
			if ($reportid = DB::result_first("SELECT id FROM #__common_report WHERE urlkey='$urlkey' AND opuid='0'")) {
				DB::query("UPDATE #__common_report SET message=CONCAT_WS('<br>', message, '$message'), num=num+1 WHERE id='$reportid'");
			} else {
				DB::query("INSERT INTO #__common_report(url, urlkey, uid, username, message, dateline) VALUES ('$url', '$urlkey', '$_G[uid]', '$_G[username]', '$message', '" . TIMESTAMP . "')");
				if ($_G['setting']['report_receive']) {
					$report_receive = explode(',', $_G['setting']['report_receive']);
					foreach ($report_receive as $touid) {
						notification_add($touid, 'report', 'new_report', array('from_id' => 1, 'from_idtype' => 'newreport'), 1);
					}
				}
			}
			showmessage('Report success.', '', array(), array('closetime' => 3, 'showdialog' => 1));
		}
		include_once libfile('function/cache');
		updatecache('modreasons');
		require_once libfile('function/misc');
		include template('common/report');
	}

	function onSendMail() {
		global $_G;

		$pernum = 1;
		require_once libfile('function/mail');
		if (!sendmail($value['email'], $subject, $message)) {
			runlog('sendmail', "$value[email] sendmail failed.");
		}
	}

}
